<?php 
require "vuelta.config.php";

require "vuelta_queries.php";

require "print_progress.php";
$report = Array();

$db = Vuelta::get_database_connection();

$query = "SELECT account.id, account.name ,account.email
          FROM account
          WHERE activated='1';";
$r = $db->query($query);
while($row = mysql_fetch_row($r)){
    $id = $row[0];
    $name = $row[1];
    $email = $row[2];
    $report[$id] = Array();
    $report[$id]['Naam speler']=$name;
    $report[$id]['Email']=$email;
    $ret[$id] = $name;
}


foreach($report as $key=>$value){
  $query = "SELECT runner.name
            FROM runner, chosen
            WHERE chosen.Account='$key' 
            AND  chosen.Runner=runner.id;";
  $iterator = 1;
  $r = $db->query($query);
  while($row = mysql_fetch_row($r)){
    $runner_name = $row[0];
    $report[$key]["Gekozen renner nr$iterator"] = $runner_name;
    $iterator++;
  }
}

foreach($report as $key=>$value){
  $query = "SELECT runner.name, top.number
            FROM runner, top 
            WHERE top.Account='$key' 
            AND  top.Runner=runner.id
            ORDER BY top.number;";
  $r = $db->query($query);
  while($row = mysql_fetch_row($r)){
    $runner_name = $row[0];
    $runner_number = $row[1];
    $report[$key]["Top renner #$runner_number"] = $runner_name;
  }
}

foreach($report as $key=>$value){
  $query = "SELECT runner.name 
            FROM runner, sprinter 
            WHERE sprinter.Account='$key' 
            AND  sprinter.Runner=runner.id;";
  $r = $db->query($query);
  if($row = mysql_fetch_row($r)){
    $runner_name = $row[0];
    $report[$key]['Sprinter'] = $runner_name;
  }
}

foreach($report as $key=>$value){
  $query = "SELECT runner.name 
            FROM runner, climber 
            WHERE climber.Account='$key' 
            AND  climber.Runner=runner.id;";
  $r = $db->query($query);
  if($row = mysql_fetch_row($r)){
    $runner_name = $row[0];
    $report[$key]['Climber'] = $runner_name;
  }
}

$runners = get_runners($db);

$to = 'mickfreeze@gmail.com';
$subject = 'rapport Vueltaspel';
$from = 'noreply@mightydev.nl';
$headers = "From:" . $from;
$message = "Rapport Vueltaspel\n";

$message = $message. "Overzicht renners:\n";
foreach($runners as $runner){
  $message = $message."\t$runner\n";
}

$message = $message. "Spelers:\n";
foreach($report as $key=>$arr){
  $state = is_selection_complete($db , $key)? "COMPLEET": "INCOMPLEET";
  $message = $message . "\tStatus inschrijving: $state\n";
  foreach($arr as $index=>$value){
    $message = $message. "\t$index:\t$value\n";
  }
  $message = $message. "\n------------------------\n";
}




mail($to, $subject, $message, $headers);
echo $message;


$db->close();

?>
